package com.tplentiful.log.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldSort;
import co.elastic.clients.elasticsearch._types.SortMode;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import com.tplentiful.log.exception.BizException;
import com.tplentiful.log.pojo.es.LogRes;
import com.tplentiful.log.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: tplentiful
 * @Since: 1.0
 **/
@Slf4j
@Service("searchServiceImpl")
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchClient client;

    public List<LogRes> simpleSearch() {
        List<String> indices = Collections.singletonList("sys_log-2022.01");
        SearchRequest searchRequest = SearchRequest.of(
                r -> r.sort(SortOptions.of(
                                b -> b.field(FieldSort.of(
                                        f -> f.field("@timestamp").mode(SortMode.Min)))))
                        .index(indices));
        try {
            SearchResponse<LogRes> search = client.search(searchRequest, LogRes.class);
            HitsMetadata<LogRes> hits1 = search.hits();
            List<Hit<LogRes>> hits = hits1.hits();
            List<LogRes> logResList = new ArrayList<>();
            for (Hit<LogRes> hit : hits) {
                logResList.add(hit.source());
            }
            return logResList;
        } catch (IOException e) {
            log.error("查询错误", e);
            throw new BizException("查询错误");
        }
    }
}
